/**
  ******************************************************************************
  * @file    hw_config.c
  * @author  MCD Application Team
  * @version V4.0.0
  * @date    21-January-2013
  * @brief   Hardware Configuration & Setup
  ******************************************************************************
  * @attention
  *
  * <h2><center>&copy; COPYRIGHT 2013 STMicroelectronics</center></h2>
  *
  * Licensed under MCD-ST Liberty SW License Agreement V2, (the "License");
  * You may not use this file except in compliance with the License.
  * You may obtain a copy of the License at:
  *
  *        http://www.st.com/software_license_agreement_liberty_v2
  *
  * Unless required by applicable law or agreed to in writing, software 
  * distributed under the License is distributed on an "AS IS" BASIS, 
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
  *
  ******************************************************************************
  */


/* Includes ------------------------------------------------------------------*/

// #include "stm32_it.h"
// #include "usb_lib.h"
// #include "usb_prop.h"
// #include "usb_desc.h"
// #include "hw_config.h"
// #include "usb_pwr.h"

#include "usb_lib.h"
#include "usb_prop.h"
#include "usb_desc.h"
#include "usb_istr.h"
#include "hw_config.h"
#include "usb_pwr.h" 
#include "usart.h"  
#include "string.h"	
#include "stdarg.h"		 
#include "stdio.h"

/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
// ErrorStatus HSEStartUpStatus;
// USART_InitTypeDef USART_InitStructure;
// EXTI_InitTypeDef EXTI_InitStructure;
// uint8_t  USART_Rx_Buffer [USART_RX_DATA_SIZE]; 
// uint32_t USART_Rx_ptr_in = 0;
// uint32_t USART_Rx_ptr_out = 0;
// uint32_t USART_Rx_length  = 0;

// uint8_t  USB_Tx_State = 0;
// static void IntToUnicode (uint32_t value , uint8_t *pbuf , uint8_t len);
// /* Extern variables ----------------------------------------------------------*/

// extern LINE_CODING linecoding;

_usb_usart_fifo uu_txfifo;			//USB串口发送FIFO结构体,在hw_config.h定义
 
u8  USART_PRINTF_Buffer[USB_USART_REC_LEN];//usb_printf发送缓冲区

//用类似串口1(串口通信实验)接收数据的方法,来处理USB虚拟串口接收到的数据.
u8 USB_USART_RX_BUF[USB_USART_REC_LEN]; //接收缓冲,最大USART_REC_LEN个字节

//接收状态
//bit15，	接收完成标志
//bit14，	接收到0x0d
//bit13~0，	接收到的有效字节数目
u16 USB_USART_RX_STA=0;       		//接收状态标记

extern LINE_CODING linecoding;		//USB虚拟串口配置信息(波特率,位数等),在usb_prop.c定义



//USB唤醒中断服务函数
void USBWakeUp_IRQHandler(void) 
{
	EXTI_ClearITPendingBit(EXTI_Line18);//清除USB唤醒中断挂起位
} 

//USB中断处理函数
void USB_LP_CAN1_RX0_IRQHandler(void) 
{
	USB_Istr();
} 

/* Private function prototypes -----------------------------------------------*/
/* Private functions ---------------------------------------------------------*/
/*******************************************************************************
* Function Name  : Set_System
* Description    : Configures Main system clocks & power
* Input          : None.
* Return         : None.
*******************************************************************************/
// 函数 void Set_System(void) 未用到，直接去除。
// void Set_System(void)
// {
//  #if !defined(STM32L1XX_MD) && !defined(STM32L1XX_HD) && !defined(STM32L1XX_MD_PLUS)
//   GPIO_InitTypeDef GPIO_InitStructure;
//  #endif /* STM32L1XX_MD && STM32L1XX_XD */  

//  #if defined(USB_USE_EXTERNAL_PULLUP)
//   GPIO_InitTypeDef  GPIO_InitStructure;
//  #endif /* USB_USE_EXTERNAL_PULLUP */ 
  
//   /*!< At this stage the microcontroller clock setting is already configured, 
//        this is done through SystemInit() function which is called from startup
//        file (startup_stm32f10x_xx.s) before to branch to application main.
//        To reconfigure the default setting of SystemInit() function, refer to
//        system_stm32f10x.c file
//      */   
//  #if defined(STM32L1XX_MD) || defined(STM32L1XX_HD)|| defined(STM32L1XX_MD_PLUS) || defined(STM32F37X) || defined(STM32F30X)
//   /* Enable the SYSCFG module clock */
//   RCC_APB2PeriphClockCmd(RCC_APB2Periph_SYSCFG, ENABLE);
//  #endif /* STM32L1XX_XD */ 
   
//  #if !defined(STM32L1XX_MD) && !defined(STM32L1XX_HD) && !defined(STM32L1XX_MD_PLUS) && !defined(STM32F37X) && !defined(STM32F30X)
//   /* Enable USB_DISCONNECT GPIO clock */
//   RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIO_DISCONNECT, ENABLE);

//   /* Configure USB pull-up pin */
//   GPIO_InitStructure.GPIO_Pin = USB_DISCONNECT_PIN;
//   GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
//   GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_OD;
//   GPIO_Init(USB_DISCONNECT, &GPIO_InitStructure);
//  #endif /* STM32L1XX_MD && STM32L1XX_XD */
   
//  #if defined(USB_USE_EXTERNAL_PULLUP)
//   /* Enable the USB disconnect GPIO clock */
//   RCC_AHBPeriphClockCmd(RCC_AHBPeriph_GPIO_DISCONNECT, ENABLE);

//   /* USB_DISCONNECT used as USB pull-up */
//   GPIO_InitStructure.GPIO_Pin = USB_DISCONNECT_PIN;
//   GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT;
//   GPIO_InitStructure.GPIO_Speed = GPIO_Speed_2MHz;
//   GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
//   GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;
//   GPIO_Init(USB_DISCONNECT, &GPIO_InitStructure);  
//  #endif /* USB_USE_EXTERNAL_PULLUP */ 
  
//  #if defined(STM32F37X) || defined(STM32F30X)
  
//   /* Enable the USB disconnect GPIO clock */
//   RCC_AHBPeriphClockCmd(RCC_AHBPeriph_GPIO_DISCONNECT, ENABLE);
  
//   /*Set PA11,12 as IN - USB_DM,DP*/
//   RCC_AHBPeriphClockCmd(RCC_AHBPeriph_GPIOA, ENABLE);
//   GPIO_InitStructure.GPIO_Pin = GPIO_Pin_11 | GPIO_Pin_12;
//   GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
//   GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
//   GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
//   GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;
//   GPIO_Init(GPIOA, &GPIO_InitStructure);
  
//   /*SET PA11,12 for USB: USB_DM,DP*/
//   GPIO_PinAFConfig(GPIOA, GPIO_PinSource11, GPIO_AF_14);
//   GPIO_PinAFConfig(GPIOA, GPIO_PinSource12, GPIO_AF_14);
  
//   /* USB_DISCONNECT used as USB pull-up */
//   GPIO_InitStructure.GPIO_Pin = USB_DISCONNECT_PIN;
//   GPIO_InitStructure.GPIO_Speed = GPIO_Speed_2MHz;
//   GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT;
//   GPIO_InitStructure.GPIO_OType = GPIO_OType_OD;
//   GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;
//   GPIO_Init(USB_DISCONNECT, &GPIO_InitStructure);
//  #endif /* STM32F37X && STM32F30X */ 
  
//   /* Configure the EXTI line 18 connected internally to the USB IP */
//   EXTI_ClearITPendingBit(EXTI_Line18);
//   EXTI_InitStructure.EXTI_Line = EXTI_Line18; 
//   EXTI_InitStructure.EXTI_Trigger = EXTI_Trigger_Rising;
//   EXTI_InitStructure.EXTI_LineCmd = ENABLE;
//   EXTI_Init(&EXTI_InitStructure);
// }

/*******************************************************************************
* Function Name  : Set_USBClock
* Description    : Configures USB Clock input (48MHz)
* Input          : None.
* Return         : None.
*******************************************************************************/
void Set_USBClock(void)
{
  //  #if defined(STM32L1XX_MD) || defined(STM32L1XX_HD) || defined(STM32L1XX_MD_PLUS) 
  //   /* Enable USB clock */
  //   RCC_APB1PeriphClockCmd(RCC_APB1Periph_USB, ENABLE);
    
  //  #else 
  //   /* Select USBCLK source */
  //   RCC_USBCLKConfig(RCC_USBCLKSource_PLLCLK_1Div5);
    
  //   /* Enable the USB clock */
  //   RCC_APB1PeriphClockCmd(RCC_APB1Periph_USB, ENABLE);
  //  #endif /* STM32L1XX_MD */

    RCC_USBCLKConfig(RCC_USBCLKSource_PLLCLK_1Div5);	   //USBclk=PLLclk/1.5=48Mhz
    RCC_APB1PeriphClockCmd(RCC_APB1Periph_USB, ENABLE);	 //USB时钟使能
}

/*******************************************************************************
* Function Name  : Enter_LowPowerMode
* Description    : Power-off system clocks and power while entering suspend mode
* Input          : None.
* Return         : None.
*******************************************************************************/
void Enter_LowPowerMode(void)
{
  // /* Set the device state to suspend */
  // bDeviceState = SUSPENDED;

  printf("usb enter low power mode\r\n");
	bDeviceState=SUSPENDED;//bDeviceState记录USB连接状态，在usb_pwr.c里面定义
}

/*******************************************************************************
* Function Name  : Leave_LowPowerMode
* Description    : Restores system clocks and power while exiting suspend mode
* Input          : None.
* Return         : None.
*******************************************************************************/
void Leave_LowPowerMode(void)
{
  // DEVICE_INFO *pInfo = &Device_Info;

  // /* Set the device state to the correct state */
  // if (pInfo->Current_Configuration != 0)
  // {
  //   /* Device configured */
  //   bDeviceState = CONFIGURED;
  // }
  // else
  // {
  //   bDeviceState = ATTACHED;
  // }
  // /*Enable SystemCoreClock*/
  // SystemInit();

  DEVICE_INFO *pInfo=&Device_Info;
	printf("leave low power mode\r\n"); 
	if (pInfo->Current_Configuration!=0)
    bDeviceState=CONFIGURED; 
	else 
    bDeviceState = ATTACHED; 

}

/*******************************************************************************
* Function Name  : USB_Interrupts_Config
* Description    : Configures the USB interrupts
* Input          : None.
* Return         : None.
*******************************************************************************/
void USB_Interrupts_Config(void) //为了兼容多个芯片，过于庸迥。
{
  //   NVIC_InitTypeDef NVIC_InitStructure; 
    
  //   /* 2 bit for pre-emption priority, 2 bits for subpriority */
  //   NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);  
    
  // #if defined(STM32L1XX_MD) || defined(STM32L1XX_HD)|| defined(STM32L1XX_MD_PLUS)
  //   NVIC_InitStructure.NVIC_IRQChannel = USB_LP_IRQn;
  //   NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 2;
  //   NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
  //   NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
  //   NVIC_Init(&NVIC_InitStructure);
    
  //     /* Enable the USB Wake-up interrupt */
  //   NVIC_InitStructure.NVIC_IRQChannel = USB_FS_WKUP_IRQn;
  //   NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
  //   NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
  //   NVIC_Init(&NVIC_InitStructure);
    
  // #elif defined(STM32F37X)
  //   /* Enable the USB interrupt */
  //   NVIC_InitStructure.NVIC_IRQChannel = USB_LP_IRQn;
  //   NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 2;
  //   NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
  //   NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
  //   NVIC_Init(&NVIC_InitStructure);
    
  //   /* Enable the USB Wake-up interrupt */
  //   NVIC_InitStructure.NVIC_IRQChannel = USBWakeUp_IRQn;
  //   NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
  //   NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
  //   NVIC_Init(&NVIC_InitStructure);
    
  // #else
  //   NVIC_InitStructure.NVIC_IRQChannel = USB_LP_CAN1_RX0_IRQn;
  //   NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 2;
  //   NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
  //   NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
  //   NVIC_Init(&NVIC_InitStructure);
    
  //     /* Enable the USB Wake-up interrupt */
  //   NVIC_InitStructure.NVIC_IRQChannel = USBWakeUp_IRQn;
  //   NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
  //   NVIC_Init(&NVIC_InitStructure);
  // #endif /* STM32L1XX_XD */

  //   /* Enable USART Interrupt */
  //   NVIC_InitStructure.NVIC_IRQChannel = EVAL_COM1_IRQn;
  //   NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 1;
  //   NVIC_Init(&NVIC_InitStructure);

  NVIC_InitTypeDef NVIC_InitStructure;
	EXTI_InitTypeDef EXTI_InitStructure; 
	/* Configure the EXTI line 18 connected internally to the USB IP */
	EXTI_ClearITPendingBit(EXTI_Line18);		//  开启线18上的中断
	EXTI_InitStructure.EXTI_Line = EXTI_Line18; 	// USB resume from suspend mode
	EXTI_InitStructure.EXTI_Trigger = EXTI_Trigger_Rising;	//line 18上事件上升降沿触发
	EXTI_InitStructure.EXTI_LineCmd = ENABLE;
	EXTI_Init(&EXTI_InitStructure); 	

	/* Enable the USB interrupt */
	NVIC_InitStructure.NVIC_IRQChannel = USB_LP_CAN1_RX0_IRQn;//组2，优先级次之 
	NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 1;
	NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
	NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
	NVIC_Init(&NVIC_InitStructure);
	
	/* Enable the USB Wake-up interrupt */
	NVIC_InitStructure.NVIC_IRQChannel = USBWakeUp_IRQn;   //组2，优先级最高	
	NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
	NVIC_Init(&NVIC_InitStructure);  	

}

/*******************************************************************************
* Function Name  : USB_Cable_Config
* Description    : Software Connection/Disconnection of USB Cable
* Input          : None.
* Return         : Status
*******************************************************************************/
// void USB_Cable_Config (FunctionalState NewState)
// {
//  #if defined(STM32L1XX_MD) || defined (STM32L1XX_HD)|| (STM32L1XX_MD_PLUS)
//   if (NewState != DISABLE)
//   {
//     STM32L15_USB_CONNECT;
//   }
//   else
//   {
//     STM32L15_USB_DISCONNECT;
//   }  
  
//  #else /* USE_STM3210B_EVAL or USE_STM3210E_EVAL */
//   if (NewState != DISABLE)
//   {
//     GPIO_ResetBits(USB_DISCONNECT, USB_DISCONNECT_PIN);
//   }
//   else
//   {
//     GPIO_SetBits(USB_DISCONNECT, USB_DISCONNECT_PIN);
//   }
//  #endif /* STM32L1XX_MD */
// }

//USB接口配置(配置1.5K上拉电阻,ALIENTEK的M3系列开发板，不需要配置,固定加了上拉电阻)
//NewState:DISABLE,不上拉，ENABLE,上拉
void USB_Cable_Config (FunctionalState NewState)
{ 
	if (NewState!=DISABLE)
    printf("usb pull up enable\r\n"); 
	else 
    printf("usb pull up disable\r\n"); 
}

//USB使能连接/断线   enable:0,断开;1,允许连接	
void USB_Port_Set(u8 enable)
{
	RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA,ENABLE);    //使能PORTA时钟	 
	if(enable)_SetCNTR(_GetCNTR()&(~(1<<1)));//退出断电模式
	else
	{	  
		_SetCNTR(_GetCNTR()|(1<<1));  // 断电模式
		GPIOA->CRH&=0XFFF00FFF;
		GPIOA->CRH|=0X00033000;
		PAout(12)=0;	    		  
	}
} 


/*******************************************************************************
* Function Name  :  USART_Config_Default.
* Description    :  configure the EVAL_COM1 with default values.
* Input          :  None.
* Return         :  None.
*******************************************************************************/
// void USART_Config_Default(void)
// {
//   /* EVAL_COM1 default configuration */
//   /* EVAL_COM1 configured as follow:
//         - BaudRate = 9600 baud  
//         - Word Length = 8 Bits
//         - One Stop Bit
//         - Parity Odd
//         - Hardware flow control disabled
//         - Receive and transmit enabled
//   */
//   USART_InitStructure.USART_BaudRate = 9600;
//   USART_InitStructure.USART_WordLength = USART_WordLength_8b;
//   USART_InitStructure.USART_StopBits = USART_StopBits_1;
//   USART_InitStructure.USART_Parity = USART_Parity_Odd;
//   USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
//   USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx;

//   /* Configure and enable the USART */
//   STM_EVAL_COMInit(COM1, &USART_InitStructure);

//   /* Enable the USART Receive interrupt */
//   USART_ITConfig(EVAL_COM1, USART_IT_RXNE, ENABLE);
// }

/*******************************************************************************
* Function Name  :  USART_Config.
* Description    :  Configure the EVAL_COM1 according to the line coding structure.
* Input          :  None.
* Return         :  Configuration status
                    TRUE : configuration done with success
                    FALSE : configuration aborted.
*******************************************************************************/
bool USART_Config(void)
{

    // /* set the Stop bit*/
    // switch (linecoding.format)
    // {
    //   case 0:
    //     USART_InitStructure.USART_StopBits = USART_StopBits_1;
    //     break;
    //   case 1:
    //     USART_InitStructure.USART_StopBits = USART_StopBits_1_5;
    //     break;
    //   case 2:
    //     USART_InitStructure.USART_StopBits = USART_StopBits_2;
    //     break;
    //   default :
    //   {
    //     USART_Config_Default();
    //     return (FALSE);
    //   }
    // }

    // /* set the parity bit*/
    // switch (linecoding.paritytype)
    // {
    //   case 0:
    //     USART_InitStructure.USART_Parity = USART_Parity_No;
    //     break;
    //   case 1:
    //     USART_InitStructure.USART_Parity = USART_Parity_Even;
    //     break;
    //   case 2:
    //     USART_InitStructure.USART_Parity = USART_Parity_Odd;
    //     break;
    //   default :
    //   {
    //     USART_Config_Default();
    //     return (FALSE);
    //   }
    // }

    // /*set the data type : only 8bits and 9bits is supported */
    // switch (linecoding.datatype)
    // {
    //   case 0x07:
    //     /* With this configuration a parity (Even or Odd) should be set */
    //     USART_InitStructure.USART_WordLength = USART_WordLength_8b;
    //     break;
    //   case 0x08:
    //     if (USART_InitStructure.USART_Parity == USART_Parity_No)
    //     {
    //       USART_InitStructure.USART_WordLength = USART_WordLength_8b;
    //     }
    //     else 
    //     {
    //       USART_InitStructure.USART_WordLength = USART_WordLength_9b;
    //     }
        
    //     break;
    //   default :
    //   {
    //     USART_Config_Default();
    //     return (FALSE);
    //   }
    // }

  // USART_InitStructure.USART_BaudRate = linecoding.bitrate;
  // USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
  // USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx;
 
  // /* Configure and enable the USART */
  // STM_EVAL_COMInit(COM1, &USART_InitStructure);

  // return (TRUE);


    uu_txfifo.readptr=0;	//清空读指针
	uu_txfifo.writeptr=0;	//清空写指针
	USB_USART_RX_STA=0;		//USB USART接收状态清零
	printf("linecoding.format:%d\r\n",linecoding.format);
  printf("linecoding.paritytype:%d\r\n",linecoding.paritytype);
	printf("linecoding.datatype:%d\r\n",linecoding.datatype);
	printf("linecoding.bitrate:%d\r\n",linecoding.bitrate);
	return (TRUE);
}

/*******************************************************************************
* Function Name  : USB_To_USART_Send_Data.
* Description    : send the received data from USB to the UART 0.
* Input          : data_buffer: data address.
                   Nb_bytes: number of bytes to send.
* Return         : none.
*******************************************************************************/
void USB_To_USART_Send_Data(uint8_t* data_buffer, uint8_t Nb_bytes)
{
  
  // uint32_t i;
  
  // for (i = 0; i < Nb_bytes; i++)
  // {
  //   USART_SendData(EVAL_COM1, *(data_buffer + i));
  //   while(USART_GetFlagStatus(EVAL_COM1, USART_FLAG_TXE) == RESET); 
  // }  

  u8 i; u8 res;

  for(i=0;i<Nb_bytes;i++)
  {  
      res=data_buffer[i]; 
      if((USB_USART_RX_STA&0x8000)==0)	//接收未完成
      {
          if(USB_USART_RX_STA&0x4000)	//接收到了0x0d
          {
                if(res!=0x0a)USB_USART_RX_STA=0;	//错误,重新开始
                else USB_USART_RX_STA|=0x8000;	//接收完成了 
            }else //还没收到0X0D
            {	
                if(res==0x0d)USB_USART_RX_STA|=0x4000;//标记接收到了0X0d
                else
                {       	          
                      USB_USART_RX_BUF[USB_USART_RX_STA&0X3FFF]=res;USB_USART_RX_STA++; 	   
                      if(USB_USART_RX_STA>(USB_USART_REC_LEN-1))USB_USART_RX_STA=0;//错误,重收
                  }					
            }
        }   
    }

}

/*******************************************************************************
* Function Name  : Handle_USBAsynchXfer.
* Description    : send data to USB.
* Input          : None.
* Return         : none.
*******************************************************************************/
// void Handle_USBAsynchXfer (void)
// {
  
//   uint16_t USB_Tx_ptr;
//   uint16_t USB_Tx_length;
  
//   if(USB_Tx_State != 1)
//   {
//     if (USART_Rx_ptr_out == USART_RX_DATA_SIZE)
//     {
//       USART_Rx_ptr_out = 0;
//     }
    
//     if(USART_Rx_ptr_out == USART_Rx_ptr_in) 
//     {
//       USB_Tx_State = 0; 
//       return;
//     }
    
//     if(USART_Rx_ptr_out > USART_Rx_ptr_in) /* rollback */
//     { 
//       USART_Rx_length = USART_RX_DATA_SIZE - USART_Rx_ptr_out;
//     }
//     else 
//     {
//       USART_Rx_length = USART_Rx_ptr_in - USART_Rx_ptr_out;
//     }
    
//     if (USART_Rx_length > VIRTUAL_COM_PORT_DATA_SIZE)
//     {
//       USB_Tx_ptr = USART_Rx_ptr_out;
//       USB_Tx_length = VIRTUAL_COM_PORT_DATA_SIZE;
      
//       USART_Rx_ptr_out += VIRTUAL_COM_PORT_DATA_SIZE;	
//       USART_Rx_length -= VIRTUAL_COM_PORT_DATA_SIZE;	
//     }
//     else
//     {
//       USB_Tx_ptr = USART_Rx_ptr_out;
//       USB_Tx_length = USART_Rx_length;
      
//       USART_Rx_ptr_out += USART_Rx_length;
//       USART_Rx_length = 0;
//     }
//     USB_Tx_State = 1; 
//     UserToPMABufferCopy(&USART_Rx_Buffer[USB_Tx_ptr], ENDP1_TXADDR, USB_Tx_length);
//     SetEPTxCount(ENDP1, USB_Tx_length);
//     SetEPTxValid(ENDP1); 
//   }  
  
// }
/*******************************************************************************
* Function Name  : UART_To_USB_Send_Data.
* Description    : send the received data from UART 0 to USB.
* Input          : None.
* Return         : none.
*******************************************************************************/
// void USART_To_USB_Send_Data(void)
// {
  
//   if (linecoding.datatype == 7)
//   {
//     USART_Rx_Buffer[USART_Rx_ptr_in] = USART_ReceiveData(EVAL_COM1) & 0x7F;
//   }
//   else if (linecoding.datatype == 8)
//   {
//     USART_Rx_Buffer[USART_Rx_ptr_in] = USART_ReceiveData(EVAL_COM1);
//   }
  
//   USART_Rx_ptr_in++;
  
//   /* To avoid buffer overflow */
//   if(USART_Rx_ptr_in == USART_RX_DATA_SIZE)
//   {
//     USART_Rx_ptr_in = 0;
//   }
// }


//发送一个字节数据到USB虚拟串口
void USB_USART_SendData(u8 data)
{
	uu_txfifo.buffer[uu_txfifo.writeptr]=data;
	uu_txfifo.writeptr++;
	if(uu_txfifo.writeptr==USB_USART_TXFIFO_SIZE)//超过buf大小了,归零.
	{
		uu_txfifo.writeptr=0;
	} 
}



/*******************************************************************************
* Function Name  : Get_SerialNum.
* Description    : Create the serial number string descriptor.
* Input          : None.
* Output         : None.
* Return         : None.
*******************************************************************************/
void Get_SerialNum(void)
{
  uint32_t Device_Serial0, Device_Serial1, Device_Serial2;

  Device_Serial0 = *(uint32_t*)ID1;
  Device_Serial1 = *(uint32_t*)ID2;
  Device_Serial2 = *(uint32_t*)ID3;  

  Device_Serial0 += Device_Serial2;

  if (Device_Serial0 != 0)
  {
    IntToUnicode (Device_Serial0, &Virtual_Com_Port_StringSerial[2] , 8);
    IntToUnicode (Device_Serial1, &Virtual_Com_Port_StringSerial[18], 4);
  }
}

/*******************************************************************************
* Function Name  : HexToChar.
* Description    : Convert Hex 32Bits value into char.
* Input          : None.
* Output         : None.
* Return         : None.
*******************************************************************************/
void IntToUnicode (uint32_t value , uint8_t *pbuf , uint8_t len)
{
  uint8_t idx = 0;
  
  for( idx = 0 ; idx < len ; idx ++)
  {
    if( ((value >> 28)) < 0xA )
    {
      pbuf[ 2* idx] = (value >> 28) + '0';
    }
    else
    {
      pbuf[2* idx] = (value >> 28) + 'A' - 10; 
    }
    
    value = value << 4;
    
    pbuf[ 2* idx + 1] = 0;
  }
}


//usb虚拟串口,printf 函数
//确保一次发送数据不超USB_USART_REC_LEN字节
void usb_printf(char* fmt,...)  
{  
	u16 i,j;
	va_list ap;
	va_start(ap,fmt);
	vsprintf((char*)USART_PRINTF_Buffer,fmt,ap);
	va_end(ap);
	i=strlen((const char*)USART_PRINTF_Buffer);//此次发送数据的长度
	for(j=0;j<i;j++)//循环发送数据
	{
		USB_USART_SendData(USART_PRINTF_Buffer[j]); 
	}
} 

/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
